package com.xexun.gpstracker.study;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;

import com.xexun.gpstracker.common.CommonRestPath;
import com.xexun.gpstracker.common.MyConstants;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenu;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuCreator;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuItem;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuListView;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.msg.adapter.MsgAdapter;
import com.xexun.gpstracker.pojo.*;
import com.xexun.gpstracker.util.*;
import com.xexun.gpstracker.vo.RelationType;
import com.xexun.gpstracker.vo.TermType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.baby.activity.ChatActivity;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.listener.MenuItemClickListener;
import com.xexun.gpstracker.my.activity.AboutUsActivity;
import com.xexun.gpstracker.my.activity.AccountActivity;
import com.xexun.gpstracker.my.activity.MessageSwitchActivity;
import com.xexun.gpstracker.view.BadgeView;
import com.xexun.gpstracker.view.PopupOptionMenu;
import com.xexun.gpstracker.vo.FlavorType;
import com.xexun.gpstracker.vo.Session;

/**
 * 在线学习页面
 *
 * @author tfx
 */
public class StudyFragment extends Fragment implements OnClickListener {
    ListView listView;
    BookAdapter bookAdapter;
    private List<Book> books = new ArrayList<>();
    private View view;
    private Context mContext;

    public static StudyFragment newInstance() {
        StudyFragment newFragment = new StudyFragment();
        return newFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        WizardAlertDialog.getInstance().showProgressDialog(R.string.loading, mContext);
        //checkStudyBooks();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_study, container, false);
        x.view().inject(this, view);
        //initEvent();

        listView = (ListView) view.findViewById(R.id.studyLv);
        listView.setDivider(new ColorDrawable(Color.BLUE));
        listView.setDividerHeight(2);

        bookAdapter = new BookAdapter(getActivity(), books);
        listView.setAdapter(bookAdapter);
        //listView.setMenuCreator(creator);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            }
        });

//        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();/*在数组中存放数据*/
//        for(int i=0;i<5;i++)
//        {
//            HashMap<String, Object> map = new HashMap<String, Object>();
//            map.put("itemName", "三国演义");
//            map.put("itemAuthor", "罗贯中");
//            map.put("itemTime", "2016-07-26");
//            map.put("itemNote", "四大名著之一");
//            listItem.add(map);
//        }
//        SimpleAdapter mSimpleAdapter = new SimpleAdapter(mContext,listItem,//需要绑定的数据
//                R.layout.item,//每一行的布局//动态数组中的数据源的键对应到定义布局的View中
//                new String[] {"itemName", "itemAuthor", "itemTime", "itemNote"},
//                new int[] {R.id.itemName,R.id.itemAuthor,R.id.itemTime,R.id.itemNote}
//            );
//        listView.setAdapter(mSimpleAdapter);//为ListView绑定适配器

       // listView.setAdapter(new ArrayAdapter<String>(mContext,
       //         android.R.layout.simple_list_item_1, strs));

        return view;
    }

    @Override
    public void onClick(View v) {

    }

    private void initEvent() {

    }


    @Override
    public void onResume() {
        super.onResume();
        //init();
        checkStudyBooks();
        bookAdapter.refreshData(books);
    }

    private void init() {
        books.clear();

        Book book = new Book("《三国演义》","罗贯中","2016-07-26","三人争天下",null,null);
        books.add(book);

        book = new Book("《水浒传》","施耐庵","2016-07-26","108个山匪对抗朝廷",null,null);
        books.add(book);

        book = new Book("《西游记》","吴承恩","2016-07-26","西天取经的故事",null,null);
        books.add(book);

        book = new Book("《红楼梦》","曹雪芹","2016-07-26","一大家族的兴衰史",null,null);
        books.add(book);

       /* for (int i = 0; i < 5; i++) {
            Book book = new Book("三国演义","罗贯中","2016-07-26","四大名著之一",null,null);

            books.add(book);
        }*/
    }

    private void checkStudyBooks() {
        try {
            JSONObject data = new JSONObject();
            data.put("page", 1);
            HttpCallback callback = new HttpCallback() {
                @Override
                public void onStart() {

                }

                @Override
                public void onFinish() {

                }

                @Override
                public void onSuccess(ResponseData obj) throws Exception {
                    WizardAlertDialog.getInstance().closeProgressDialog();
                    if (obj.getRetcode() == 1) {
                        try {
                            JSONObject object = obj.getBody();
                            int row = object.optInt("rowCount");
                            if(row <= 0)
                                return;
                            JSONArray array = object.optJSONArray("data");
                            if (array != null && array.length() > 0) {
                                books.clear();
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject jsonObject = array.getJSONObject(i);
                                    Book book = new Book();
                                    book.setId(jsonObject.getInt("id"));
                                    String url = jsonObject.optString("filePath");
                                    book.setUrl(url);
                                    book.setSuffix(url.substring(url.lastIndexOf(".")));
                                    book.setName(jsonObject.optString("name"));
                                    book.setTime(jsonObject.optString("createTime"));
                                    book.setNote(jsonObject.optString("remark"));
                                    book.setAuthor(jsonObject.optString("userName"));
                                    book.setmLocAddr(book.getFireDir()+book.getId()+book.getSuffix());
                                    books.add(book);
                                }
                                bookAdapter.refreshData(books);
                            } else {
                                Toast.makeText(mContext, R.string.loadfail, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.e(Constants.TAG, "获取列表失败！", e);
                            Toast.makeText(mContext, R.string.loadfail, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(mContext, R.string.loadfail, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(String message) throws Exception {
                    WizardAlertDialog.getInstance().closeProgressDialog();
                    Toast.makeText(mContext, R.string.loadfail, Toast.LENGTH_SHORT).show();
                }
            };
            //使用异步请求链接对象
            HttpUtil.post(CommonRestPath.studyBooksUpload(), data, new JsonHttpResponseHelper(callback).getHandler());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
